package com.zjjc.QZEnergy.utils;


import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.CollectionUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpUtils {

    private static final Logger logger = LogManager.getLogger(HttpUtils.class);

    private static CloseableHttpClient httpClient;
    private static RequestConfig requestConfig;

    static {
        // 初始化 HttpClient 和 RequestConfig
        httpClient = HttpClients.createDefault();
        requestConfig = RequestConfig.custom()
                .setSocketTimeout(5000)
                .setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000)
                .build();
    }

    /**
     * 发送POST请求
     *
     * @param url   请求URL
     * @param param 请求体
     * @return 响应字符串
     */
    public static String doPost(String url, Map<String, Object> param) {
        // 创建Http Post请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);

        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (Map.Entry<String, Object> entry : param.entrySet()) {
                    paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            logger.error("调用第三方错误:{}", e.getMessage());
        } finally {
            try {
                httpPost.abort();
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    /**
     * 发送POST请求
     *
     * @param url     请求URL
     * @param param   请求体
     * @param headers 请求头信息
     * @return 响应字符串
     */
    public static String doPost(String url, Map<String, Object> param, Map<String, String> headers) {
        // 创建Http Post请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        if (!CollectionUtils.isEmpty(headers)) {
            headers.forEach((k, v) -> httpPost.addHeader(k, v));
        }

        CloseableHttpResponse response = null;
        try {
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (Map.Entry<String, Object> entry : param.entrySet()) {
                    paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            logger.error("调用第三方错误:{}", e.getMessage());
        } finally {
            try {
                httpPost.abort();
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String doPost(String url, String jsonString, Map<String, String> headers) {
        // 创建Http Post请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);

        if (!CollectionUtils.isEmpty(headers)) {
            headers.forEach((k, v) -> httpPost.addHeader(k, v));
        }

        CloseableHttpResponse response = null;
        try {
            // 设置请求体为JSON格式
            HttpEntity entity = new StringEntity(jsonString, "UTF-8");
            // 在构造函数中已经设定了Content-Type，无需再次设定
            httpPost.addHeader("Content-Type", "application/json");

            httpPost.setEntity(entity);

            // 执行http请求
            CloseableHttpClient httpClient = HttpClients.createDefault();
            response = httpClient.execute(httpPost);
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            logger.error("调用第三方错误:{}", e.getMessage());
        } finally {
            try {
                httpPost.abort();
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}